import React from "react";
import { Form, Select, Input, Cascader, Tag } from "antd";
import GoBack from "@/components/TheGoBack";
import TheUpload from "@/components/TheUpload";
import TheButton from "@/components/TheButton";
import TheQuill from "@/components/TheQuill";
import Sku from './Sku'
import EditSku from './editSku'
import { goodsClassifyTree, goodsTagsList } from '@/request/storeBackManage/goodsManage/goodsList'
import { goodsInfoInsert, goodsInfoUpdateState } from '@/request/storeBackManage/goodsManage/centerGoodsList'
import '../style/style.scss'
import _ from 'lodash';

export default class AddGoods extends React.Component {
  constructor(props) {
    super(props)
    this.applyBrandRef = React.createRef()
    this.state = {
      productInfoJson: {}, //基本表单信息
      goodsClassifyOptions: [],//商品分类列表
      goodsTagOptions: [], //商品标签list
      templateOptions: [],//运费模板list
      skuPropertyArray: [],//商品规格数据
      skuPropertyTable: [], //商品规格表头内容
      skuType: "",
      numResult: [], // sku表格数据
      currentIndex: 1,// 当前步骤
      btnLoading: false, //发布按钮loading
      productTxt: '',//规格详细信息
      skuInfoJson: '',
      goodsId: '',//商品id
      alias: [],
      fileList: [],//图片回显
    }
  }
  componentDidMount() {
    this.getClassifyList()
    this.goodsTagsList()
  }

  // 商品类目列表
  getClassifyList = async () => {
    let res = await goodsClassifyTree()
    if (res.code === 0 && res.data) {
      this.setState({
        goodsClassifyOptions: res.data
      })
    }
  }
  // 选择商品类目
  cascaderChange = async (value, selectedOptions) => {
    if (!value || !selectedOptions) return
    const [arg, arg1, classifyId] = value
    let alias = this.state.alias
    selectedOptions.map((v) => {
      if (v.alias === null) {
        alias = ""
      } else {
        alias = alias + v.alias
      }
      return alias
    })
    this.setState({
      alias
    })
  }
  // 商品标签列表
  goodsTagsList = async () => {
    let res = await goodsTagsList({ type: "goods_tag" })
    let goodsTagOptions = res.data.map((v) => {
      return { label: v.name, value: v.dictionariesId }
    })
    this.setState({ goodsTagOptions })
  }
  // 选择适用宠物
  goodsTagChange = (props) => {
    this.formRef.setFieldsValue({ goodsTag: props })
  }
  // 上传图片
  getFileResult = (value) => {
    if (value.length) {
      let str = value.map(v => {
        if (v.response && v.response.code === 0) {
          return v.response.data
        }
      }).join(',')
      this.formRef.setFieldsValue({ goodsShowImages: str });
    } else {
      this.formRef.setFieldsValue({ goodsShowImages: '' });
    }
  };
  // 下一页上一页数据处理
  setCurrentIndex = async (current) => {
    let status = true
    await this.formRef.validateFields().catch(err => { return status = false }) //校验表单是否填写
    let productInfoJson = this.formRef.getFieldsValue() //基本信息表单数据
    console.log(productInfoJson, 'productInfoJson');
    productInfoJson.goodsClassifyId = productInfoJson.goodsClassifyId && productInfoJson.goodsClassifyId.join(',')
    productInfoJson.goodsTag = productInfoJson.goodsTag && productInfoJson.goodsTag.join(',')
    if (!status) { return React.$message({ type: 'info', content: '参数信息为必填信息' }) }
    let { skuPropertyArray, skuPropertyTable, numResult } = this.state
    //循环numResult数据判断返回的数组是否有值
    numResult = numResult && numResult.length && numResult.map(v => {
      return { ...v, isChecked: false, }
    })
    const productSkuJson = JSON.stringify({ skuPropertyTable, numResult, skuPropertyArray })
    console.log({ skuPropertyTable, numResult, skuPropertyArray }, '{ skuPropertyTable, numResult, skuPropertyArray }');
    // 判断商品规格详情内容是否填写
    const findEmpty = value => {
      value.forEach(v => {
        delete v.isChecked
        if (!v.skuOriginalPrice) {
          status = false
        }
        if (!v.skuCurrentPrice) {
          status = false
        }
        if (!v.materialName) {
          status = false
        }
        if (!v.skuWeight) {
          status = false
        }
        if (!v.imageFile) {
          status = false
        }
      })
      return status
    }
    // 商品数据是否填写
    skuPropertyArray.forEach(v => {
      if (!v.name) { return status = false }
    })
    if (!status) { return React.$message({ type: 'info', content: '规格标题不能为空' }) }
    if (!numResult || !findEmpty(numResult)) { return React.$message({ type: 'info', content: '请填写完整的SKU信息' }) }
    // 商品规格数据处理
    numResult = numResult.map(v => {
      return {
        ...v,
        skuOriginalPrice: React.$transNum(v.skuOriginalPrice, 0, 2),
        skuCurrentPrice: React.$transNum(v.skuCurrentPrice, 0, 2),
        skuWeight: React.$transNum(v.skuWeight, 0, 3),
      }
    })
    let material = /^[A-Za-z0-9]+$/;
    let flag = false
    let con = false
    let arr1 = numResult.reduce((pre, cur, index) => {
      // console.log(pre, cur);
      if (pre.includes(cur.materialId) && cur.materialId) {
        flag = true
        return pre
      }
      if (cur.materialId) {
        if (!material.test(cur.materialId)) {
          con = true
        }
      }
      pre.push(cur.materialId)
      return pre
    }, [])
    if (con) {
      return React.$message({
        type: 'info',
        content: '物料ID只能为字母和数字'
      })
    }
    if (flag) {
      return React.$message({
        type: 'info',
        content: '物料ID不能相同'
      })
    }
    // 批量商品库存数据
    let productStock = numResult.map(v => {
      return v.stock
    })
    productStock = _.sum(productStock)
    let arr = []
    if (numResult.length === 1) {
      if (skuPropertyTable[0].length > 1) {
        arr = _.zip(skuPropertyTable, numResult)
      } else {
        if (Array.prototype.isPrototypeOf(skuPropertyTable[0])) {
          arr = _.zip(skuPropertyTable[0], numResult)
        } else {
          let table = _.flatten(skuPropertyTable)
          arr = _.zip(table, numResult)
        }
      }
    } else {
      if (skuPropertyTable.length !== numResult.length) {
        arr = _.zip(_.flatten(skuPropertyTable), numResult)
      } else {
        arr = _.zip(skuPropertyTable, numResult)
      }
    }
    const skuInfo = arr.map((v, i) => {
      let skuAttribute = null
      let b = null
      if (Array.prototype.isPrototypeOf(v[0])) {
        skuAttribute = v[0].map((v, i) => {
          return {
            key: v.name,
            value: v.itemName
          }
        })
      } else if (Object.prototype.isPrototypeOf(v[0])) {
        skuAttribute = [
          {
            key: v[0].name,
            value: v[0].itemName
          }
        ]
      }
      if (Object.prototype.isPrototypeOf(v[1])) {
        b = v[1]
      }
      return {
        ...b,
        skuAttribute,
      }
    })
    console.log(productSkuJson, 'productSkuJson');
    this.setState({
      skuInfoJson: JSON.stringify(skuInfo),
      productSkuJson, //规格信息
      productStock, //商品库存
      productInfoJson, // 基本信息
    })
    if (status) this.setState({ currentIndex: current });//当前步骤
  }
  //获取sku返回值
  getSkuProperty = (skuPropertyArray, skuPropertyTable, skuType) => {
    let arr = [];
    if (skuPropertyTable.length > 0) {
      if (
        Object.prototype.toString.call(skuPropertyTable[0]) ===
        "[object Object]"
      ) {
        skuPropertyTable.forEach((v) => {
          arr.push(v);
        });
        arr = [arr];
      } else {
        arr = skuPropertyTable;
      }
    }
    this.setState({ skuPropertyArray, skuPropertyTable: arr, skuType });
  };
  //获取sku价格返回值
  getNumResult = (numResult) => {
    this.setState({ numResult });
  };
  // 填写详情内容
  setNewsContent = (data) => {
    const len = data.replace(/(<p>|<\/p>)/g, '').trim().length
    console.log(len, 'productTxt');
    if (!len) {
      this.setState({ productTxt: "" })
    } else {
      this.setState({ productTxt: data })
    }
    // this.setState({ productTxt: data })
  };
  // 发布
  onSubmit = async () => {
    this.setState({ btnLoading: true })
    if (this.state.currentIndex === 2) {
      if (!this.state.productTxt.trim()) {
        this.setState({ btnLoading: false })
        return React.$message({
          type: 'info',
          content: '商品规格信息为必填信息'
        })
      } else {
        let { productInfoJson, productSkuJson, productTxt, skuInfoJson, productStock } = this.state
        let goodsInfoJson = JSON.stringify({ ...productInfoJson, productSkuJson, productTxt, productStock })
        let res = await goodsInfoInsert({ goodsInfoJson, skuInfoJson })
        if (res.code === 0 && res.data) {
          let response = await goodsInfoUpdateState({ goodsId: res.data, reviewStatus: 'S' })
          if (response.code === 0) {
            React.$message({ type: 'info', content: '新商品发布成功' })
            this.props.history.goBack()
          }
        }
      }
    }
    this.setState({ btnLoading: false })
  }
  // 保存
  onSave = async () => {
    this.setState({ btnLoading: true })
    if (this.state.currentIndex === 2) {
      if (!this.state.productTxt.trim()) {
        this.setState({ btnLoading: false })
        return React.$message({
          type: 'info',
          content: '商品规格信息为必填信息'
        })
      } else {
        let { productInfoJson, productSkuJson, productTxt, skuInfoJson, productStock, goodsId } = this.state
        console.log(productInfoJson, productSkuJson, productTxt, skuInfoJson, 'productInfoJson, productSkuJson, productTxt, skuInfoJson,');
        let goodsInfoJson = JSON.stringify({ ...productInfoJson, productSkuJson, productTxt, productStock })
        let res = await goodsInfoInsert({ goodsInfoJson, skuInfoJson })
        if (res.code === 0 && res.data) {
          React.$message({ type: 'info', content: '商品保存成功' })
          this.props.history.goBack()
        }
      }
    }
    this.setState({ btnLoading: false })
  }
  render() {
    const { goodsClassifyOptions, goodsTagOptions, currentIndex, btnLoading, fileList, alias, productSkuJson, skuInfo, productTxt } = this.state
    return (
      <div className="p-layout-box content-list" >
        <GoBack history={this.props.history} title={"新增商品"} />
        <div style={{ display: currentIndex === 1 ? "block" : "none" }}>
          <div className="content-title">基本信息</div>
          <div className="content-form-box">
            <Form ref={ref => this.formRef = ref} labelCol={{ span: 5 }}>
              <Form.Item label="商品名称" name={'goodsName'} rules={[{ required: true }]}>
                <Input maxLength={60} placeholder="请输入商品名称" />
              </Form.Item>
              <Form.Item label="适用宠物" name={'goodsTag'} rules={[{ required: true }]}>
                <Select showSearch allowClear options={goodsTagOptions} mode={"multiple"} onChange={(e) => { this.goodsTagChange(e); }} placeholder="请选择适用宠物" />
              </Form.Item>
              <Form.Item label="商品类目" name={'goodsClassifyId'} rules={[{ required: true }]}>
                <Cascader placeholder="请选择商品类目" onChange={(value, selectedOptions) => this.cascaderChange(value, selectedOptions)} options={goodsClassifyOptions} />
              </Form.Item>
              <Form.Item label="商品图片" name={'goodsShowImages'} rules={[{ required: true }]} >
                <TheUpload getFileResult={this.getFileResult} len={5} fileList={fileList} />
              </Form.Item>
            </Form>
          </div>
          <div className="content-title">商品规格信息</div>
          <Sku getSkuProperty={this.getSkuProperty} getNumResult={this.getNumResult} alias={alias} />
        </div>
        <div style={{ display: currentIndex === 2 ? "block" : "none" }}>
          <div className="content-title">商品规格信息</div>
          <div style={{ width: '90%', margin: 'auto' }}>
            {_.isEmpty(productTxt) && <TheQuill style={{ height: 500 }} defaultValue={''} setNewsContent={this.setNewsContent} />}
            {!_.isEmpty(productTxt) && <TheQuill style={{ height: 500 }} defaultValue={productTxt} setNewsContent={this.setNewsContent} />}
          </div>
        </div>
        <div className="button-group" >
          <TheButton type="default" size="middle" onClick={() => { this.props.history.go(-1); }}>取消</TheButton>
          {currentIndex === 1 && <TheButton type="default" size="middle" onClick={() => this.setCurrentIndex(2)}>下一页</TheButton>}
          {currentIndex === 2 && (
            <div >
              <TheButton type="default" size="middle" onClick={() => this.setCurrentIndex(1)} > 上一步 </TheButton>
              <TheButton type="default" size="middle" onClick={this.onSave} loading={btnLoading}  >保存</TheButton>
              <TheButton type="default" size="middle" onClick={this.onSubmit} loading={btnLoading} >保存并发布</TheButton>
            </div>
          )}
        </div>
      </div>
    )
  }
}